package org.eden.rpc.service.serviceImpl.blog;

import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.exceptions.PersistenceException;
import org.apache.ibatis.session.SqlSession;
import org.eden.rpc.common.entity.dao.Tag;
import org.eden.rpc.common.service.blog.TagService;
import org.eden.rpc.service.dao.SqlSessionFactoryHolder;
import org.eden.rpc.service.dao.blog.TagMapper;

@Slf4j
public class TagServiceImpl implements TagService {

    @Override
    public Long addTag(Tag tag) {
        if (tag.getName() == null || "".equals(tag.getName())) {
            return -1L;
        }
        try (SqlSession sqlSession = SqlSessionFactoryHolder.get().openSession(true)) {
            TagMapper tagMapper = sqlSession.getMapper(TagMapper.class);
            int rows = tagMapper.insertTag(tag);
            if (rows > 0) {
                return tag.getId();
            }
        } catch (PersistenceException e) {
            log.error(e.getMessage());
        }
        return -1L;
    }

    @Override
    public Tag getTag(Long id) {
        try (SqlSession sqlSession = SqlSessionFactoryHolder.get().openSession(true)) {
            TagMapper tagMapper = sqlSession.getMapper(TagMapper.class);
            return tagMapper.getById(id);
        } catch (PersistenceException e) {
            log.error(e.getMessage());
        }
        return null;
    }
}
